package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"internal/util"
)

var mysql_ *MysqlConn

// MysqlConn 定义mysql参数结构体
type MysqlConn struct {
	host     string
	port     int
	user     string
	password string
	dbname   string
	conn     *gorm.DB
}

func InitMysqlConn() {
	mysql_ = &MysqlConn{
		host:     "82.156.87.105",
		port:     3306,
		user:     "homed",
		password: "123456",
		dbname:   "fk_school",
	}
	mysql_.connect()
	mysql_.CreateTables()
}

func (m *MysqlConn) connect() error {
	dns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", m.user, m.password, m.host, m.port, m.dbname)
	db, err := gorm.Open(mysql.Open(dns), &gorm.Config{
		Logger: util.NewGormLogger(),
	})
	util.LogSrv.Debug("[InitMysql]: ConArgs: %s", dns)
	if err != nil {
		util.LogSrv.Error("[InitMysql] mysql connect err: ", err)
		return err
	}
	sqlDB, err := db.DB()
	if err != nil {
		util.LogSrv.Error("[InitMysql] sqlDB get pointer fail! err: ", err)
	}
	util.LogSrv.Info("[InitMysql] mysql connect success!")

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(1000)
	sqlDB.SetConnMaxLifetime(30)
	m.conn = db
	return nil
}

func (m *MysqlConn) CreateTables() error { return nil }

func (m *MysqlConn) GetConn() *gorm.DB { return m.conn }

func GetConn() *gorm.DB { return mysql_.GetConn() }
